package edu.must.uh.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeHepler {

    
    public static List<Map<String, Object>>  getTreeJson(List<Map<String, Object>> sourseList,String id,String parentId,String name) { 
        
        List<Map<String, Object>> treeList = new ArrayList<Map<String,Object>>();
        Map<String, Object> tree = new HashMap<String, Object>(); 
        for (Map<String, Object> Map : sourseList) {      
            tree = new HashMap<String, Object>();
            tree.put("id", Map.get(id));
            tree.put("parentId",Map.get(parentId));
            tree.put("text", Map.get(name));  
            
            tree.put("isexpand",true); 
            tree.put("complete", true);         
            if(TreeHepler.hasChil(Map.get(id) ,sourseList,parentId)) {             
                tree.put("hasChildren",true); 
            } else {
                tree.put("hasChildren",false);
            }            
            treeList.add(tree);            
        }
        
        return TreeHepler.toTreeJson(treeList,"0");
        
    }
    
    
    public static List<Map<String, Object>>  toTreeJson(List<Map<String, Object>> treeList,String parentid) {       
        List<Map<String, Object>> restreeList = new ArrayList<Map<String,Object>>();
        for (Map<String, Object> map : treeList) {
            String parentidString =ToolsOfString.NulltoEmpty(map.get("parentId"));
            if(parentidString.equals(parentid)) {  
                if((boolean) map.get("hasChildren")) {
                    map.put("ChildNodes", toTreeJson(treeList,map.get("id").toString())) ; 
                }else {
                    map.put("ChildNodes", null) ;  
                }
                restreeList.add(map);                
            }
        }
        return restreeList;
        
    }
    
    public static boolean  hasChil(Object id,List<Map<String, Object>> data,String fielString  ) {
        boolean reString = false;
        if(Tools.notEmpty(id)) {
            for (Map<String, Object> map : data) {
                String parentidString =ToolsOfString.NulltoEmpty(map.get(fielString));
                if(id.toString().equals(parentidString)) {
                    return true;
                  }
            }            
        }
        return reString;        
    }
    
}
